//
//  JPushHandler.swift
//  TestWorkSpace
//
//  Created by Mac on 2020/1/7.
//  Copyright © 2020 jhf. All rights reserved.
//

import UIKit
import CooperSwift

class JPushHandler: NSObject, JPUSHRegisterDelegate {
    
    static let shared = JPushHandler()
    
    func configJpush(launchOptions: [UIApplication.LaunchOptionsKey: Any]?) {
        //推送代码
        let entity = JPUSHRegisterEntity()
        entity.types = 1 << 0 | 1 << 1 | 1 << 2
        JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
        //需要IDFA 功能，定向投放广告功能
        //let advertisingId = ASIdentifierManager.shared().advertisingIdentifier.uuidString
        // 95f27cd67eca75e78a485ee4    a40f58025e6d6a82165ae641
        JPUSHService.setup(withOption: launchOptions, appKey: "95f27cd67eca75e78a485ee4", channel: "App Store", apsForProduction: false, advertisingIdentifier: nil)
    }
    
    private func setJPushAlias () {
        let  alias : String = UserDefaults.standard.value(forKey: "phoneN") as! String
        JPUSHService.setAlias(alias, completion: { (iResCode, iAlias, seq) in
            print("alias,\(alias) . completion,\(iResCode),\(String(describing: iAlias)),\(seq)")
        }, seq: 0)
        JPUSHService.deleteAlias({ (iResCode, iAlias, seq) in
            print("退出注销极光别名儿 \(iResCode),\(String(describing: iAlias)),\(seq)")
        }, seq: 0)
    }
    
    
    // MARK: - JPUSHRegisterDelegate
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, openSettingsFor notification: UNNotification!) {
        log.debug(notification ?? "")
    }
    
    func jpushNotificationAuthorization(_ status: JPAuthorizationStatus, withInfo info: [AnyHashable : Any]!) {
        log.debug(info ?? "")
    }
    
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
        log.debug(notification ?? "")
        let userInfo = notification.request.content.userInfo
        if notification.request.trigger is UNPushNotificationTrigger {
            JPUSHService.handleRemoteNotification(userInfo)
        }
        // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
        completionHandler(Int(UNNotificationPresentationOptions.alert.rawValue))
    }
    
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
        log.debug(response ?? "")
        let userInfo = response.notification.request.content.userInfo
        if response.notification.request.trigger is UNPushNotificationTrigger {
            JPUSHService.handleRemoteNotification(userInfo)
        }
        // 系统要求执行这个方法
        completionHandler()
    }
    
}
